'''
Created on Jul 29, 2013

@author: Petko
'''
from threading import Timer
from sent.opinion import process_nested_set_pending_operations
from StringIO import StringIO
from sent.utils.sent_logger import sent_logger
from sent.utils import ErrorIds
import time
import json

logger = sent_logger( __name__ )

class CommitScheduler():
    '''
    classdocs
    '''
    

    def __init__(self):
        '''
        Constructor
        '''
        self.START_INTERVAL=10
        self.commit_interval=self.START_INTERVAL
        self.timer = None
    
    def execute_commit(self):
        out_msg = StringIO()
        cmn_result = process_nested_set_pending_operations(out_msg, 0)
        
        logger.log(sent_logger.INFO, "Nested set processing completed. " 
                       + json.dumps(cmn_result.result) 
                       + " status: " + str(cmn_result.errorId)
                       + " output: " + out_msg.getvalue())
        
        if cmn_result.errorId == ErrorIds.SUCCESS:
            #reschedule
            self.commit_interval = self.commit_interval / 2
            self.timer = Timer(self.commit_interval, self.execute_commit)
            self.timer.start()
            self.start_time = time.time()
        else:
            #nothing more to process
            self.commit_interval = self.START_INTERVAL
            self.timer = None
            
    def schedule_commit(self):
        if self.timer:
            self.commit_interval = self.commit_interval / 2
            next_execution_time = self.start_time + self.timer.interval
            current_time = time.time()
            next_execution_time_shrinked = current_time + self.commit_interval
            if next_execution_time < current_time or next_execution_time > next_execution_time_shrinked:
                self.timer.cancel()
            else:
                #the timer will execute sooner anyways
                return
        self.timer = Timer(self.commit_interval, self.execute_commit)
        self.timer.start()
        self.start_time = time.time()
        

g_commit_scheduler = CommitScheduler()
